import os
import datetime
from selenium import webdriver
import time
import csv
import traceback
from django.http import JsonResponse
from common.error import *
from django.conf import settings
import random
import uuid


def get_driver(faddress, driver):
    if driver == 'chrome':
        option = webdriver.ChromeOptions()
        option.add_argument('headless')  # 设置option
        broswer2 = webdriver.Chrome(options=option,
                                    executable_path=faddress + '/chromedriver.exe')
    elif driver == 'firefox':
        option = webdriver.FirefoxOptions()
        option.add_argument('--headless')  # 设置option
        broswer2 = webdriver.Firefox(options=option,
                                     executable_path=faddress + '/geckodriver.exe')
    return broswer2


def get_overview(code_start, code_end, faddress, driver):
    uu_id = str(uuid.uuid1())
    today = datetime.datetime.now().strftime('%Y-%m-%d')
    temp_path = '/file/finance/' + today + '/' + uu_id + "/overview/"
    result = {'dahui': '', 'jiben': '', 'faxing': ''}
    if not os.path.exists(faddress + temp_path):
        os.makedirs(faddress + temp_path)
    for k in range(int(code_start), int(code_end) + 1):
        introBaseurl = 'http://f10.eastmoney.com/f10_v2/CompanySurvey.aspx?code='
        Baseurl = 'http://f10.eastmoney.com/f10_v2/CompanyBigNews.aspx?code='
        k = str(k).rjust(6, '0')
        try:
            url = introBaseurl + str('sh' + k)
            broswer2 = get_driver(faddress, driver)
            broswer2.get(url)
            title = broswer2.title
            if title == '无F10资料':
                broswer2.quit()
                url = introBaseurl + str('sz' + k)
                broswer2 = get_driver(faddress, driver)
                broswer2.get(url)
                print("深圳股")
            else:
                print("上海股")
            try:
                time.sleep(random.uniform(0, 1))
                daima = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[4]/td[1]')
                daima = str(daima.text)
            except:
                daima = '--'
                # 代码
            try:
                mingcheng = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[1]/td')
                # 名称
                mingcheng = str(mingcheng.text)
            except:
                mingcheng = '--'
                # 英文名称
            try:
                yingwenmingcheng = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[2]/td')
                yingwenmingcheng = str(yingwenmingcheng.text)
            except:
                yingwenmingcheng = '--'
                # 曾用名
            try:
                cengyongming = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[3]/td')
                cengyongming = str(cengyongming.text)
            except:
                cengyongming = '--'
                # 简称
            try:
                jiancheng = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[4]/td[2]')
                if jiancheng.text == '--':
                    jiancheng = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[5]/td[2]')
                jiancheng = str(jiancheng.text)
            except:
                jiancheng = '--'
                # 证券类型
            try:
                zhengjuanleixing = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[7]/td[1]')
                zhengjuanleixing = str(zhengjuanleixing.text)
            except:
                zhengjuanleixing = '--'
                # 上市交易所
            try:
                shangshijiaoyisuo = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[8]/td[1]')
                shangshijiaoyisuo = str(shangshijiaoyisuo.text)
            except:
                shangshijiaoyisuo = '--'
                # 证监会行业
            try:
                zhengjianhui = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[8]/td[2]')
                zhengjianhui = str(zhengjianhui.text)
            except:
                zhengjianhui = '--'
                # 法人代表
            try:
                farendaibiao = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[9]/td[2]')
                farendaibiao = str(farendaibiao.text)
            except:
                farendaibiao = '--'
                # 事物代表
            try:
                shiwudaibiao = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[11]/td[1]')
                shiwudaibiao = str(shiwudaibiao.text)
            except:
                shiwudaibiao = '--'
                # 办公地址
            try:
                bangongdizhi = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[14]/td[1]')
                bangongdizhi = str(bangongdizhi.text)
            except:
                bangongdizhi = '--'
                # 注册地址
            try:
                zhucedizhi = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[14]/td[2]')
                zhucedizhi = str(zhucedizhi)
            except:
                zhucedizhi = '--'
                # 邮政编码
            try:
                youzhengbianma = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[15]/td[2]')
                youzhengbianma = str(youzhengbianma.text)
            except:
                youzhengbianma = '--'
                # 注册资本
            try:
                zhuceziben = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[16]/td[1]')
                zhuceziben = str(zhuceziben.text)
            except:
                zhuceziben = '--'
                # 工商登记
            try:
                gongshangdengji = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[16]/td[2]')
                gongshangdengji = str(gongshangdengji.text) + '\t'
            except:
                gongshangdengji = '--'
                # 雇员人数
            try:
                guyuanrenshu = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[17]/td[1]')
                guyuanrenshu = str(guyuanrenshu.text)
            except:
                guyuanrenshu = '--'
                # 律师事务所
            try:
                lvshishiwusuo = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[18]/td[1]')
                lvshishiwusuo = str(lvshishiwusuo.text)
            except:
                lvshishiwusuo = '--'
                # 会计师事务所
            try:
                kuaijishi = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[18]/td[2]')
                kuaijishi = str(kuaijishi.text)
            except:
                kuaijishi = '--'
                # 独立董事
            try:
                dulidongshi = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[11]/td[2]')
                dulidongshi = str(dulidongshi.text)
            except:
                dulidongshi = '--'
            try:
                dongshizhang = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[10]/td[2]')
                # 董事长
                dongshizhang = str(dongshizhang.text)
            except:
                dongshizhang = '--'
            try:
                hangye = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[7]/td[2]')
                # 行业
                hangye = str(hangye.text)
            except:
                hangye = '--'
            try:
                guanlirenyuan = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[17]/td[2]')
                # 管理人员人数
                guanlirenyuan = str(guanlirenyuan.text)
            except:
                guanlirenyuan = '--'
            try:
                time.sleep(random.uniform(0, 1))
                qvyu = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[15]/td[1]')
                # 区域
                qvyu = str(qvyu.text)
            except:
                qvyu = '--'
            try:
                dongmi = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[10]/td[1]')
                # 董秘
                dongmi = str(dongmi.text)
            except:
                dongmi = '--'
            try:
                lianxidianhua = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[12]/td[1]')
                lianxidianhua = str(lianxidianhua.text)
            except:
                lianxidianhua = '--'
            try:
                zongjingli = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[9]/td[1]')
                # 总经理
                zongjingli = str(zongjingli.text)
            except:
                zongjingli = '--'
            try:
                wangzhi = broswer2.find_element_by_xpath('//*[@id="CompanyWebId"]')
                # 网址
                wangzhi = str(wangzhi.text)
            except:
                wangzhi = '--'
                # 简介
            try:
                gongsijianjie = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[19]/td')
                gongsijianjie = str(gongsijianjie.text)
            except:
                gongsijianjie = '--'
                # 经营范围
            try:
                jingyingfanwei = broswer2.find_element_by_xpath('//*[@id="Table0"]/tbody/tr[20]/td')
                jingyingfanwei = str(jingyingfanwei.text)
            except:
                jingyingfanwei = '--'
            try:
                chengliriqi = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[1]/td[1]')
                chengliriqi = str(chengliriqi.text)
            except:
                chengliriqi = '--'
                # 上市日期
            try:
                shangshiriqi = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[1]/td[2]')
                shangshiriqi = str(shangshiriqi.text)
            except:
                shangshiriqi = '--'
                # 发行市盈率
            try:
                faxingshiyinglv = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[2]/td[1]')
                faxingshiyinglv = str(faxingshiyinglv.text)
            except:
                faxingshiyinglv = '--'
                # 网上发行日期
            try:
                wangshangfaxingriqi = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[2]/td[2]')
                wangshangfaxingriqi = str(wangshangfaxingriqi.text)
            except:
                wangshangfaxingriqi = '--'
                # 发行方式
            try:
                faxingfangshi = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[3]/td[1]')
                faxingfangshi = str(faxingfangshi.text)
            except:
                faxingfangshi = '--'
                # 每股面值
            try:
                meigumianzhi = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[3]/td[2]')
                meigumianzhi = str(meigumianzhi.text)
            except:
                meigumianzhi = '--'
                # 发行量
            try:
                faxingliang = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[4]/td[1]')
                faxingliang = str(faxingliang.text)
            except:
                faxingliang = '--'
                # 每股发行价
            try:
                faxingjia = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[4]/td[2]')
                faxingjia = str(faxingjia.text)
            except:
                faxingjia = '--'
                # 发行费用
            try:
                faxingfeiyong = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[5]/td[1]')
                faxingfeiyong = str(faxingfeiyong.text)
            except:
                faxingfeiyong = '--'
                # 发行总市值
            try:
                faxingzongshizhi = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[5]/td[2]')
                faxingzongshizhi = str(faxingzongshizhi.text)
            except:
                faxingzongshizhi = '--'
                # 募集资金净额
            try:
                jinge = broswer2.find_element_by_xpath('//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[6]/td[1]')
                jinge = str(jinge.text)
            except:
                jinge = '--'
                # 首日开盘价
            try:
                kaipanjia = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[6]/td[2]')
                kaipanjia = str(kaipanjia.text)
            except:
                kaipanjia = '--'
                # 首日收盘价
            try:
                shoupanjia = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[7]/td[1]')
                shoupanjia = str(shoupanjia.text)
            except:
                shoupanjia = '--'

                # 首日换手率
            try:
                time.sleep(random.uniform(0, 1))
                huanshoulv = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[7]/td[2]')

                huanshoulv = str(huanshoulv.text)
            except:
                huanshoulv = '--'
                # 首日最高价
            try:
                zuigaojia = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[8]/td[1]')
                zuigaojia = str(zuigaojia.text)
            except:
                zuigaojia = '--'
                # 网下配售中签率
            try:
                wangxiazhongqianlv = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[8]/td[2]')
                wangxiazhongqianlv = str(wangxiazhongqianlv.text)
            except:
                wangxiazhongqianlv = '--'
                # 定价中签率
            try:
                dingjiazhongqianlv = broswer2.find_element_by_xpath(
                    '//*[@id="templateDiv"]/div[2]/div[2]/table/tbody/tr[9]/td')
                dingjiazhongqianlv = str(dingjiazhongqianlv.text)
            except:
                dingjiazhongqianlv = '--'
            broswer2.quit()
            # 调用带参数的谷歌浏览器
            url = Baseurl + str('sh' + k)
            broswer2 = get_driver(faddress, driver)
            broswer2.get(url)
            title = broswer2.title
            if title == '无F10资料':
                broswer2.quit()
                # 调用带参数的谷歌浏览器
                url = Baseurl + str('sz' + k)
                broswer2 = get_driver(faddress, driver)
                broswer2.get(url)
            else:
                print("上海股")
            try:
                time.sleep(random.uniform(0, 1))
                # 最近除权除息:
                cqcx = broswer2.find_element_by_xpath('//*[@id="dstxDiv"]/table/tbody/tr[1]/td[2]/span')
                cqcx = str(cqcx.text)
            except:
                cqcx = "--"
            try:
                time.sleep(random.uniform(1, 2))
                # 最近分配方案:
                fpfa = broswer2.find_element_by_xpath('//*[@id="dstxDiv"]/table/tbody/tr[2]/td[2]/span')
                fpfa = str(fpfa.text)
            except:
                fpfa = "--"
            try:
                time.sleep(random.uniform(1, 2))
                # 最近股东大会:
                gddh = broswer2.find_element_by_xpath('//*[@id="dstxDiv"]/table/tbody/tr[3]/td[2]')
                gddh = str(gddh.text)
            except:
                gddh = "--"
            broswer2.quit()

            try:  # lynn 开始保存了
                if not os.path.exists(faddress + temp_path + "公司大会.csv"):
                    filedahui(faddress + temp_path + "公司大会.csv")
                with open(faddress + temp_path + "公司大会.csv", 'a+', encoding='utf-8', newline='') as csvfile:
                    writer = csv.writer(csvfile)
                    writer.writerow(
                        [daima, mingcheng, dongshizhang, hangye, guanlirenyuan,
                         qvyu, dongmi, lianxidianhua, zongjingli, wangzhi,
                         gongsijianjie, jingyingfanwei, cqcx, fpfa, gddh])
            except Exception as e:  # changed by lynn
                print("公司大会csv存入出错")

            try:
                if not os.path.exists(faddress + temp_path + "基本资料.csv"):
                    filejiben(faddress + temp_path + "基本资料.csv")
                with open(faddress + temp_path + "基本资料.csv", 'a+', encoding='utf-8', newline='') as csvfile1:
                    writer = csv.writer(csvfile1)
                    # 代码 名称 英文名 曾用名 简称 证券类别 行业 上市交易所 证监会 总经理 法人代表 董秘 董事长 事务代表 独立董事 网址 办公地址 区域 注册资本 工商登记 雇员人数 管理人数 律师事务所 会计师事务所 公司简介 经营范围,邮政编码，联系电话
                    writer.writerow([daima, mingcheng, yingwenmingcheng, cengyongming,
                                     jiancheng,
                                     zhengjuanleixing, hangye, shangshijiaoyisuo,
                                     zhengjianhui,
                                     zongjingli, farendaibiao, dongmi, dongshizhang,
                                     shiwudaibiao,
                                     dulidongshi, wangzhi, bangongdizhi, qvyu,
                                     zhuceziben,
                                     gongshangdengji, guyuanrenshu, guanlirenyuan,
                                     lvshishiwusuo,
                                     kuaijishi, gongsijianjie, jingyingfanwei, youzhengbianma, lianxidianhua])
            except Exception as e:  # changed by lynn
                print("基本资料csv存入出错")

            try:
                if not os.path.exists(faddress + temp_path + "发行相关.csv"):
                    filefaxing(faddress + temp_path + "发行相关.csv")
                with open(faddress + temp_path + "发行相关.csv", 'a+', encoding='utf-8', newline='') as csvfile2:
                    writer = csv.writer(csvfile2)
                    #  成立日期 上市日期 市盈率 发行日期 发行方式 每股面值 发行量 发行费用 发行总市值 募集资金净额 首日开盘价 首日收盘价 首日换手率 首日最高价 网下配售中签率 定价中签率
                    writer.writerow([daima, chengliriqi, shangshiriqi, faxingshiyinglv,
                                     wangshangfaxingriqi, faxingfangshi, meigumianzhi,
                                     faxingliang, faxingfeiyong, faxingzongshizhi,
                                     jinge, kaipanjia, shoupanjia, huanshoulv,
                                     zuigaojia, wangxiazhongqianlv,
                                     dingjiazhongqianlv])
            except Exception as e:  # changed by lynn
                print("发行相关csv存入出错")

        except Exception as e:  # changed by lynn
            info = {
                'successful': False,
                'data': result,
                'code': ERROR_CODE_PARTNER_ERROR,
                'message': '爬虫脚本出错'
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
    result.update(
        {'dahui': temp_path + "公司大会.csv", 'jiben': temp_path + "基本资料.csv",
         'faxing': temp_path + "发行相关.csv"})
    info = {
        'successful': True,
        'data': result,
        'code': ERROR_CODE_OPERATION_SUCCESS,
        'message': '数据获取成功'
    }
    return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


def filedahui(name):  # 大会资料
    with open(name, 'w+', encoding='utf-8', newline='') as f:
        csv_writer = csv.writer(f)
        csv_writer.writerow(
            ['股票代码', '名称', '董事长', '行业', '管理人员', '区域', '董秘', '联系电话', '总经理', '网址', '公司简介', '经营范围', '除股除息', '分配方案',
             '股东大会'])


def filejiben(name):  # 基本信息
    with open(name, 'w+', encoding='utf-8', newline='') as f:
        csv_writer = csv.writer(f)
        csv_writer.writerow(
            ['代码', '名称', '英文名', '曾用名', '简称', '证券类别', '行业', '上市交易所', '证监会', '总经理', '法人代表', '董秘', '董事长', '事务代表', '独立董事',
             '网址', '办公地址', '区域', '注册资本', '工商登记', '雇员人数', '管理人数', '律师事务所', '会计师事务所', '公司简介', '经营范围', '邮政编码', '联系电话'])


def filefaxing(name):  # 发行相关
    with open(name, 'w+', encoding='utf-8', newline='') as f:
        csv_writer = csv.writer(f)
        csv_writer.writerow(
            ['股票代码', '成立日期', '上市日期', '市盈率', '发行日期', '发行方式', '每股面值', '发行量', '发行费用', '发行总市值', '募集资金净额', '首日开盘价', '首日收盘价',
             '首日换手率', '首日最高价', '网下配售中签率', '定价中签率'])


def get_compare(code_start, code_end, faddress, driver):  # 爬取各个公司信息
    uu_id = str(uuid.uuid1())
    today = datetime.datetime.now().strftime('%Y-%m-%d')
    temp_path = '/file/finance/' + today + '/' + uu_id + "/compare/"
    result = {'chengzhang': '', 'guzhi': '', 'dubang': ''}
    if not os.path.exists(faddress + temp_path):
        os.makedirs(faddress + temp_path)
    for k in range(int(code_start), int(code_end) + 1):
        introBaseurl = "http://f10.eastmoney.com/IndustryAnalysis/Index?type=web&code="
        daima = str(k).rjust(6, '0')
        try:
            broswer = get_driver(faddress, driver)
            url = introBaseurl + str('SH' + daima + "#")
            broswer.get(url)
            time.sleep(1)
            title = broswer.title
            if title == '无F10资料':
                broswer.quit()
                broswer = get_driver(faddress, driver)
                url = introBaseurl + str('SZ' + daima + "#")
                broswer.get(url)
                time.sleep(1)
            try:
                paiming = broswer.find_element_by_xpath(
                    '/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[1]').text
            except:
                paiming = '--'
            try:
                # time.sleep(1)
                daima = broswer.find_element_by_xpath(
                    '/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[2]').text
            except:
                daima = '--'
            try:
                # time.sleep(1)
                name = broswer.find_element_by_xpath(
                    '/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[3]').text
            except:
                name = '--'
            try:
                # time.sleep(1)
                fuhe31 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[4]").text
            except:
                fuhe31 = '--'
            try:
                # time.sleep(1)
                A191 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[5]").text
            except:
                A191 = '--'
            try:
                # time.sleep(1)
                TTM1 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[6]").text
            except:
                TTM1 = '--'
            try:
                # time.sleep(1)
                E201 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[7]").text
            except:
                E201 = '--'
            try:
                # time.sleep(1)
                E211 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[8]").text
            except:
                E211 = '--'
            try:
                # time.sleep(1)
                E221 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[9]").text
            except:
                E211 = '--'
            try:
                # time.sleep(1)
                fuhe32 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[10]").text
            except:
                fuhe32 = '--'
            try:
                # time.sleep(1)
                A192 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[11]").text
            except:
                A192 = '--'
            try:
                # time.sleep(1)
                TTM2 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[12]").text
            except:
                TTM2 = '--'
            try:
                # time.sleep(1)
                E202 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[13]").text
            except:
                E202 = '--'
            try:
                # time.sleep(1)
                E212 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[14]").text
            except:
                E212 = '--'
            try:
                # time.sleep(1)
                E222 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[15]").text
            except:
                E222 = '--'
                # 估值
            try:
                # time.sleep(1)
                paiming2 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[1]").text
            except:
                paiming2 = '--'
            try:
                # time.sleep(1)
                PEG = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[4]").text
            except:
                PEG = '--'
            try:
                # time.sleep(1)
                A1911 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[5]").text
            except:
                A1911 = '--'
            try:
                # time.sleep(1)
                TTM11 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[6]").text
            except:
                TTM11 = '--'
            try:
                # time.sleep(1)
                E2011 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[7]").text
            except:
                E2011 = '--'
            try:
                # time.sleep(1)
                E2111 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[8]").text
            except:
                E211 = '--'
            try:
                # time.sleep(1)
                E2211 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[9]").text
            except:
                E2211 = '--'
            try:
                # time.sleep(1)
                A1921 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[10]").text
            except:
                A1921 = '--'
            try:
                # time.sleep(1)
                TTM21 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[11]").text
            except:
                TTM21 = '--'
            try:
                # time.sleep(1)
                E2021 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[12]").text
            except:
                E2021 = '--'
            try:
                # time.sleep(1)
                E2121 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[13]").text
            except:
                E2121 = '--'
            try:
                # time.sleep(1)
                E2221 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[3]/div[2]/table/tbody/tr[3]/td[14]").text
            except:
                E2221 = '--'

                # 杜邦
            try:
                # time.sleep(1)
                paiming3 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[4]/div[2]/table/tbody/tr[3]/td[1]").text
            except:
                paiming3 = '--'
            try:
                # time.sleep(1)
                pj3n = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[4]/div[2]/table/tbody/tr[3]/td[4]").text
            except:
                pj3n = '--'
            try:
                # time.sleep(1)
                A17 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[4]/div[2]/table/tbody/tr[3]/td[5]").text
            except:
                A17 = '--'
            try:
                # time.sleep(1)
                A18 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[4]/div[2]/table/tbody/tr[3]/td[6]").text
            except:
                A18 = '--'
            try:
                # time.sleep(1)
                A1912 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[4]/div[2]/table/tbody/tr[3]/td[7]").text
            except:
                A1912 = '--'
            try:
                # time.sleep(1)
                pj3n2 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[4]/div[2]/table/tbody/tr[3]/td[8]").text
            except:
                pj3n2 = '--'
            try:
                # time.sleep(1)
                A172 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[4]/div[2]/table/tbody/tr[3]/td[9]").text
            except:
                A172 = '--'
            try:
                # time.sleep(1)
                A182 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[4]/div[2]/table/tbody/tr[3]/td[10]").text
            except:
                A182 = '--'
            try:
                # time.sleep(1)
                A1922 = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[4]/div[2]/table/tbody/tr[3]/td[11]").text
            except:
                A1922 = '--'
            broswer.quit()
            introBaseurl = "http://f10.eastmoney.com/CompanySurvey/Index?type=web&code="
            broswer = get_driver(faddress, driver)
            url = introBaseurl + str('SH' + daima + "#")
            try:
                broswer.get(url)
                time.sleep(1)
            except:
                print("网址打开有误")
                title = broswer.title
            if title == '无F10资料':
                broswer.quit()
                broswer = get_driver(faddress, driver)
                url = introBaseurl + str('SZ' + daima + "#")
                broswer.get(url)
                time.sleep(1)
                print("深圳股")
            else:
                print("上海股")
            try:
                time.sleep(1)
                hangye = broswer.find_element_by_xpath(
                    "/html/body/div[1]/div[2]/div[2]/div[1]/div[2]/table/tbody/tr[7]/td[2]").text
            except:
                hangye = '--'
            broswer.quit()
            try:  # lynn 开始保存了
                if not os.path.exists(faddress + temp_path + "成长性比较.csv"):
                    filechengzhang(faddress + temp_path + "成长性比较.csv")
                with open(faddress + temp_path + "成长性比较.csv", 'a+', encoding='utf-8', newline='') as f:
                    csv_writer = csv.writer(f)
                    dm1 = '#' + daima
                    csv_writer.writerow(
                        [hangye, paiming, dm1, name, fuhe31, A191, TTM1, E201, E211, E221, fuhe32, A192, TTM2, E202,
                         E212,
                         E222])
            except Exception as e:  # changed by lynn
                print("成长性比较csv存入出错")
            try:
                if not os.path.exists(faddress + temp_path + "估值比较.csv"):
                    fileguzhi(faddress + temp_path + "估值比较.csv")
                with open(faddress + temp_path + "估值比较.csv", 'a+', encoding='utf-8', newline='') as f:
                    csv_writer = csv.writer(f)
                    csv_writer.writerow(
                        [hangye, paiming2, dm1, name, PEG, A1911, TTM11, E2011, E2111, E2211, A1921, TTM21, E2021,
                         E2121, E2221])
            except Exception as e:
                print("估值比较csv存入出错")
            try:
                if not os.path.exists(faddress + temp_path + "杜邦分析比较.csv"):
                    filedubang(faddress + temp_path + "杜邦分析比较.csv")
                with open(faddress + temp_path + "杜邦分析比较.csv", 'a+', encoding='utf-8', newline='') as f:
                    csv_writer = csv.writer(f)
                    csv_writer.writerow([hangye, paiming3, dm1, name, pj3n, A17, A18, A1912, pj3n2, A172, A182, A1922])
            except Exception as e:
                print("杜邦分析比较csv存入出错")
        except Exception as e:
            info = {
                'successful': False,
                'data': result,
                'code': ERROR_CODE_PARTNER_ERROR,
                'message': '爬虫脚本出错'
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
    result.update(
        {'chengzhang': temp_path + "成长性比较.csv", 'guzhi': temp_path + "估值比较.csv",
         'dubang': temp_path + "杜邦分析比较.csv"})
    info = {
        'successful': True,
        'data': result,
        'code': ERROR_CODE_OPERATION_SUCCESS,
        'message': '数据获取成功'
    }
    return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


def filechengzhang(name):  # 改为成长
    with open(name, 'w+', encoding='utf-8', newline='') as f:
        csv_writer = csv.writer(f)
        csv_writer.writerow(['', '', '', '', '基本每股收益增长率（%）', '', '', '', '', '', '营业收入增长率(%)', '', '', '', '', ''])
        csv_writer.writerow(
            ['行业', '排名/属性', '代码', '简称', '3年复合', '20A', 'TTM', '21E', '22E', '23E', '3年复合', '20A', 'TTM', '21E', '22E',
             '23E'])


def fileguzhi(name):  # 改为估值
    with open(name, 'w+', encoding='utf-8', newline='') as f:
        csv_writer = csv.writer(f)
        csv_writer.writerow(['', '', '', '', '', '市盈率', '', '', '', '', '市销率', '', '', '', ''])
        csv_writer.writerow(
            ['行业', '排名/属性', '代码', '简称', 'PEG', '20A', 'TTM', '21E', '22E', '23E', '20A', 'TTM', '21E', '22E', '23E'])


def filedubang(name):  # 改为杜邦
    with open(name, 'w+', encoding='utf-8', newline='') as f:
        csv_writer = csv.writer(f)
        csv_writer.writerow(['', '', '', '', 'ROE(%)', '', '', '', '净利率（%）', '', '', ''])
        csv_writer.writerow(['行业', '排名/属性', '代码', '简称', '3年平均', '18A', '19A', '20A', '3年平均', '18A', '19A', '20A'])


def get_finance(code_start, code_end, type, faddress, driver):
    if type == 'overview':
        return get_overview(code_start, code_end, faddress, driver)
    elif type == 'compare':
        return get_compare(code_start, code_end, faddress, driver)


if __name__ == '__main__':
    a = '000001'
    b = '000002'
    get_overview(a, b, '')
